package info.rongtong.service.impl;

import info.rongtong.domain.Article;
import info.rongtong.domain.Picture;
import info.rongtong.domain.Review;
import info.rongtong.service.basic.BasicServiceImpl;
import info.rongtong.service.inter.ReviewServiceInter;

import java.util.ArrayList;
import java.util.List;

public class ReviewServiceImpl extends BasicServiceImpl implements
		ReviewServiceInter {

	public List<Review> getReviewListByCategory(Integer id, Class clazz,
			Integer pageSize, Integer pageNow) {
		String hql = "";
		Object[] obj = { id };
		if (clazz == Article.class) {
			hql = "from Review where aid=? order by rtime desc";
		} else if (clazz == Picture.class) {
			hql = "from Review where pid=? order by rtime desc";
		}
		return this.executeQuery(Review.class, hql, obj, pageNow, pageSize);
	}

	public Integer getReviewListByCategoryCount(Integer Id, Class clazz,
			Integer pageSize) {
		String hql = "";
		Object[] obj = { Id };
		if (clazz == Article.class) {
			hql = "select count(*) from Review where aid=?";
		} else if (clazz == Picture.class) {
			hql = "select count(*) from Review where pid=?";
		}
		Integer temp = Integer.parseInt(this.uniqueResult(hql, obj).toString());
		return ((temp - 1) / pageSize + 1);
	}

	/**
	 * 模拟\测试递归的算法
	 */

	public List getReviewListByCategory2(Integer id, Class clazz,Integer pageSize,Integer pageNow) {
		String hql = "";
		Object[] obj = { id };
		if (clazz == Article.class) {
			hql = "from Review where aid=? order by rtime desc";
		} else if (clazz == Picture.class) {
			hql = "from Review where pid=? order by rtime desc";
		}
		List<Review> list = new ArrayList<Review>(); //this.executeQuery(Review.class, hql, obj, pageNow, pageSize);
		List<Review> listL = this.executeQuery(Review.class, hql, obj);
		for(int i=(pageNow-1)*pageSize;i<pageSize*pageNow;i++){
			if(i<listL.size())
				list.add(listL.get(i));
		}
		List list2 = new ArrayList();
		for (Review r : list) {
			if (r.getParentId() != null) {
				list2.add(this.getReviewListByLiss(r, listL));
			} else
				list2.add(r);
		}
		return list2;
	}

	public List getReviewListByLiss(Review review, List<Review> liss) {
		List list = new ArrayList();
		for (Review r : liss) {
			if (r.getRid().equals(review.getParentId())) {
				if (r.getParentId() != null) {
					list.add(this.getReviewListByLiss(r, liss));
					list.add(review);
					return list;
				} else if (review.getParentId() != null) {
					list.add(this.getReviewListByLiss(r, liss));
					list.add(review);
					return list;
				}
			}
		}
		list.add(review);
		return list;
	}

}
